<template>
  <div class="commission-edit">
    <a-alert v-if="hasError" :message="errorMessage" type="warning" show-icon closable @close="hasError = false" />
    <div class="options">
      <a-radio-group v-model:value="option" :style="{ marginBottom: '8px' }">
        <a-radio-button :value="1">
          <a-space>
            <input class="radio-view" type="radio" :checked="option === 1" @click="option = 1" />
            Previous Version
          </a-space>
        </a-radio-button>
        <a-radio-button :value="2">
          <a-space>
            <input class="radio-view" type="radio" :checked="option === 2" @click="option = 2" />
            New Version(Overseas)
          </a-space>
        </a-radio-button>
      </a-radio-group>
      <div>
        <span style="color: rgba(107, 121, 142, 0.85)">Currency : </span>
        <span style="font-size: 16px; font-weight: bold">{{ props.rawData.currencyName }}</span>
      </div>
    </div>
    <e-title title="Year Factor" style="margin-top: 18px" />
    <div class="year-factor">
      <year-factor-inline
        v-for="index in 4"
        :key="index"
        v-model:from="saveData.yearPercents[index - 1].minYear"
        v-model:to="saveData.yearPercents[index - 1].maxYear"
        v-model:factor="saveData.yearPercents[index - 1].yearPercent"
        :is-last="index - 1 === 3"
      />
    </div>
    <div style="display: flex">
      <a-space>
        <e-title title="Configuration" />
        <a-select
          v-if="option === 2"
          v-model:value="saveData.yearQuotaPercent.sYear"
          :options="yearOptions"
          @change="handleYearChange"
        />
      </a-space>
    </div>
    <div v-if="option === 1" class="configuration">
      <amount-factor-inline
        v-for="index in 4"
        :key="index"
        v-model:from="saveData.amountPercents[index - 1].minPrice"
        v-model:to="saveData.amountPercents[index - 1].maxPrice"
        v-model:factor="saveData.amountPercents[index - 1].moneyPercent"
        :is-last="index - 1 === 3"
      />
    </div>
    <div v-else class="configuration overseas">
      <a-spin :spinning="monthLoading">
        <a-row :gutter="[48, 14]" wrap>
          <a-col :span="24" class="field-text">
            <a-space>
              <span>Year Quota</span>
              <a-tooltip>
                <template #title>
                  The commission for existing accounts will be 3.5% under sales quota, and 5% for meeting above annual
                  sales.
                </template>
                <e-icon type="tips" style="cursor: help" />
              </a-tooltip>
            </a-space>
          </a-col>
          <a-col :span="24">
            <a-input-number
              v-model:value="saveData.yearQuotaPercent.salesQuota"
              :min="0"
              style="width: 50%"
              :precision="2"
              :controls="false"
              :disabled="monthEditable.some(item => item === false)"
            />
          </a-col>
        </a-row>
        <a-divider dashed />
        <a-row :gutter="[24, 16]" wrap>
          <a-col :span="24" class="field-text">
            <a-space>
              <span> Monthly Quota</span>
              <monthly-quota-tooltip />
            </a-space>
          </a-col>
          <a-col v-for="item in saveData.monthPercent" :key="item.sMonth" :span="6">
            <a-input-number
              v-model:value="saveData.monthPercent[item.sMonth - 1].salesQuota"
              :precision="2"
              :min="0"
              :controls="false"
              :disabled="!monthEditable[item.sMonth - 1]"
            >
              <template #addonBefore>
                <span class="field-text month-addon">{{ Utils.numberToMonth(item.sMonth - 1, true) }}</span>
              </template>
            </a-input-number>
          </a-col>
        </a-row>
      </a-spin>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { cloneDeep } from 'lodash-es'
import ETitle from '@/components/ETitle.vue'
import MonthlyQuotaTooltip from '@/pages/components/MonthlyQuotaTooltip.vue'
import YearFactorInline from './yearFactorInline.vue'
import AmountFactorInline from './amountFactorInline.vue'
import Utils from '@/utils/index.js'
import CommissionRate from '@/api/commissionRate.js'
const props = defineProps({
  rawData: {
    type: Object,
    default() {
      return {}
    }
  }
})
// 1 为原始计算方法 2为新计算方法
const option = ref(1)
// 年份
const yearOptions = ref([
  {
    value: new Date().getFullYear() - 1,
    label: new Date().getFullYear() - 1
  },
  {
    value: new Date().getFullYear(),
    label: new Date().getFullYear()
  },
  {
    value: new Date().getFullYear() + 1,
    label: new Date().getFullYear() + 1
  }
])
// 表单验证
const hasError = ref(false)
const errorMessage = ref('')
const saveData = reactive({
  employee: null,
  yearPercents: [
    { minYear: 0, maxYear: null, yearPercent: null },
    { minYear: null, maxYear: null, yearPercent: null },
    { minYear: null, maxYear: null, yearPercent: null },
    { minYear: null, maxYear: 50, yearPercent: null }
  ],
  amountPercents: [
    { minPrice: 0, maxPrice: null, moneyPercent: null },
    { minPrice: null, maxPrice: null, moneyPercent: null },
    { minPrice: null, maxPrice: null, moneyPercent: null },
    { minPrice: null, maxPrice: 100000000000, moneyPercent: null }
  ],
  yearQuotaPercent: {
    employee: null,
    sYear: new Date().getFullYear(),
    salesQuota: null
  },
  monthPercent: [
    {
      employee: null,
      sYear: null,
      sMonth: 1,
      salesQuota: null
    },
    {
      employee: null,
      sYear: null,
      sMonth: 2,
      salesQuota: null
    },
    {
      employee: null,
      sYear: null,
      sMonth: 3,
      salesQuota: null
    },
    {
      employee: null,
      sYear: null,
      sMonth: 4,
      salesQuota: null
    },
    {
      employee: null,
      sYear: null,
      sMonth: 5,
      salesQuota: null
    },
    {
      employee: null,
      sYear: null,
      sMonth: 6,
      salesQuota: null
    },
    {
      employee: null,
      sYear: null,
      sMonth: 7,
      salesQuota: null
    },
    {
      employee: null,
      sYear: null,
      sMonth: 8,
      salesQuota: null
    },
    {
      employee: null,
      sYear: null,
      sMonth: 9,
      salesQuota: null
    },
    {
      employee: null,
      sYear: null,
      sMonth: 10,
      salesQuota: null
    },
    {
      employee: null,
      sYear: null,
      sMonth: 11,
      salesQuota: null
    },
    {
      employee: null,
      sYear: null,
      sMonth: 12,
      salesQuota: null
    }
  ]
})
const monthLoading = ref(true)
const monthEditable = reactive([true, false, false, false, false, false, false, false, false, false, false, false])
let rawData
// 初始化年数据数据
const initMonthPercentWithYear = () => {
  const year = saveData.yearQuotaPercent.sYear
  // 月系数
  saveData.monthPercent.forEach(item => {
    item.sYear = year
    const result = rawData.yearQuotas.find(quota => {
      return quota.sYear === year && quota.sMonth === item.sMonth
    })
    if (result) {
      item.salesQuota = result.salesQuota
    } else {
      item.salesQuota = null
    }
  })
  // 年系数
  const result = rawData.yearQuotas.find(quota => {
    return quota.sYear === year && quota.sMonth === 0
  })
  if (result) {
    saveData.yearQuotaPercent.salesQuota = result.salesQuota
  } else {
    saveData.yearQuotaPercent.salesQuota = null
  }
}
// 或缺月份可编辑情况
const getMonthEditable = () => {
  monthEditable.forEach((value, index) => (monthEditable[index] = false))
  CommissionRate.getCanEditMonth(saveData.employee, saveData.yearQuotaPercent.sYear)
    .then(({ data }) => {
      data.forEach(item => {
        monthEditable[item.month - 1] = item.flag
      })
    })
    .finally(() => {
      monthLoading.value = false
    })
}
// 初始化方法
const init = () => {
  rawData = cloneDeep(props.rawData)
  option.value = rawData.performSale && rawData.performSale.calculationType ? rawData.performSale.calculationType : 1
  saveData.employee = rawData.employee
  saveData.yearQuotaPercent.employee = rawData.employee
  saveData.monthPercent.forEach(item => {
    item.employee = rawData.employee
  })
  if (Array.isArray(rawData.yearPercents) && rawData.yearPercents.length === 4) {
    rawData.yearPercents.forEach((item, index) => {
      saveData.yearPercents[index] = item
    })
  }
  if (Array.isArray(rawData.salesAmountPercents) && rawData.salesAmountPercents.length === 4) {
    rawData.salesAmountPercents.forEach((item, index) => {
      saveData.amountPercents[index] = item
    })
  }
  /*
  if (Array.isArray(rawData.yearQuotas) && rawData.yearQuotas.length > 0) {
    initMonthPercentWithYear()
  }
   */
  initMonthPercentWithYear()
  getMonthEditable()
}
// 最大值最小值联动
watch(
  () => saveData.yearPercents,
  () => {
    saveData.yearPercents[1].minYear = saveData.yearPercents[0].maxYear
    saveData.yearPercents[2].minYear = saveData.yearPercents[1].maxYear
    saveData.yearPercents[3].minYear = saveData.yearPercents[2].maxYear
  },
  {
    deep: true
  }
)
watch(
  () => saveData.amountPercents,
  () => {
    saveData.amountPercents[1].minPrice = saveData.amountPercents[0].maxPrice
    saveData.amountPercents[2].minPrice = saveData.amountPercents[1].maxPrice
    saveData.amountPercents[3].minPrice = saveData.amountPercents[2].maxPrice
  },
  {
    deep: true
  }
)
// 年份改动
const handleYearChange = year => {
  initMonthPercentWithYear(year)
  getMonthEditable()
}
const validate = () => {
  hasError.value = false
  return new Promise((resolve, reject) => {
    // 存在空值
    if (saveData.yearPercents.some(item => item.maxYear === null || item.yearPercent === null)) {
      hasError.value = true
      errorMessage.value = 'Please complete required field - Year Factor.'
      reject(new Error('Form validate error.'))
      return
    }
    // 范围大小错误
    if (
      saveData.yearPercents.some(
        (item, index) => index !== 3 && item.maxYear - saveData.yearPercents[index + 1].maxYear >= 0
      )
    ) {
      hasError.value = true
      errorMessage.value = 'The data you entered is invalid - Year Factor.'
      reject(new Error('Form validate error.'))
      return
    }
    if (option.value === 1) {
      if (saveData.amountPercents.some(item => item.maxPrice === null || item.moneyPercent === null)) {
        hasError.value = true
        errorMessage.value = 'Please complete required field - Configuration.'
        reject(new Error('Form validate error.'))
        return
      }
      if (
        saveData.amountPercents.some(
          (item, index) => index !== 3 && item.maxPrice - saveData.amountPercents[index + 1].maxPrice >= 0
        )
      ) {
        hasError.value = true
        errorMessage.value = 'The data you entered is invalid - Configuration.'
        reject(new Error('Form validate error.'))
        return
      }
    }
    if (option.value === 2) {
      if (saveData.yearQuotaPercent.salesQuota === null) {
        hasError.value = true
        errorMessage.value = 'Please complete required field - Year Quota.'
        reject(new Error('Form validate error.'))
        return
      }
      if (saveData.monthPercent.some(item => item.salesQuota === null)) {
        hasError.value = true
        errorMessage.value = 'Please complete required field - Monthly Quota.'
        reject(new Error('Form validate error.'))
        return
      }
    }
    resolve({
      option: option.value,
      employee: saveData.employee,
      yearPercents: saveData.yearPercents,
      amountPercents: saveData.amountPercents,
      yearQuotaPercent: saveData.yearQuotaPercent,
      monthPercent: saveData.monthPercent
    })
  })
}
defineExpose({ init, validate })
</script>

<style lang="less" scoped>
.commission-edit {
  .options {
    margin-top: 14px;
    display: flex;
    justify-content: space-between;
    .radio-view {
      width: unset;
      height: unset;
      opacity: 1;
      pointer-events: auto;
      vertical-align: middle;
      color: @primary-color;
      margin-top: -2px;
      &:after {
        background-color: red;
      }
    }
  }
  .configuration,
  .year-factor {
    padding: 24px 8px;
    .year-factor-inline,
    .configuration-inline {
      &:not(:first-child) {
        margin-top: 16px;
      }
    }
    :deep(.field-text) {
      color: rgba(129, 141, 159, 1);
      &.month-addon {
        display: inline-block;
        width: 32px;
      }
    }
  }
  .configuration {
    padding: 24px 8px 0 8px;
    &.overseas {
      :deep(.ant-descriptions-item-label) {
        background-color: @milk;
        color: #818d9f;
      }
      :deep(.ant-descriptions-item-content) {
        padding: 16px;
      }
    }
  }
}
</style>
